/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.xjbweekly.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jfinal.kit.Kv;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.core.consts.SymbolConstant;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.login.LoginEmpInfo;
import vip.xiaonuo.core.pojo.login.SysLoginUser;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.xjbweekly.entity.XjbWeekly;
import vip.xiaonuo.modular.xjbweekly.enums.XjbWeeklyExceptionEnum;
import vip.xiaonuo.modular.xjbweekly.mapper.XjbWeeklyMapper;
import vip.xiaonuo.modular.xjbweekly.param.XjbWeeklyParam;
import vip.xiaonuo.modular.xjbweekly.service.XjbWeeklyService;
import vip.xiaonuo.sys.modular.dict.param.SysDictTypeParam;
import vip.xiaonuo.sys.modular.dict.service.SysDictDataService;
import vip.xiaonuo.sys.modular.dict.service.SysDictTypeService;
import vip.xiaonuo.sys.modular.org.entity.SysOrg;
import vip.xiaonuo.sys.modular.org.enums.SysOrgExceptionEnum;
import vip.xiaonuo.sys.modular.org.param.SysOrgParam;
import vip.xiaonuo.sys.modular.org.service.SysOrgService;
import vip.xiaonuo.util.ZpWordUtil;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 周报汇总表service接口实现类
 *
 * @author zhangping
 * @date 2022-03-11 10:48:51
 */
@Service
public class XjbWeeklyServiceImpl extends ServiceImpl<XjbWeeklyMapper, XjbWeekly> implements XjbWeeklyService {

    @Resource
    private SysOrgService sysOrgService;

    @Override
    public PageResult<XjbWeekly> page(XjbWeeklyParam xjbWeeklyParam) {
        QueryWrapper<XjbWeekly> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(xjbWeeklyParam)) {

            // 根据组织机构 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getOrgs())) {
                queryWrapper.lambda().eq(XjbWeekly::getOrgs, xjbWeeklyParam.getOrgs());
            }
            // 根据任务类型 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getType())) {
                queryWrapper.lambda().eq(XjbWeekly::getType, xjbWeeklyParam.getType());
            }
            // 根据任务编号 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getTaskcode())) {
                queryWrapper.lambda().eq(XjbWeekly::getTaskcode, xjbWeeklyParam.getTaskcode());
            }
            // 根据任务子类型 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getType2())) {
                queryWrapper.lambda().eq(XjbWeekly::getType2, xjbWeeklyParam.getType2());
            }
            // 根据任务名称 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getTitle()) /*&& xjbWeeklyParam.getTitle().length() >= 3*/) {
                queryWrapper.lambda().like(XjbWeekly::getTitle, xjbWeeklyParam.getTitle());  // like
            }
            // 根据任务明细 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getContent())) {
                queryWrapper.lambda().like(XjbWeekly::getContent, xjbWeeklyParam.getContent());
            }
            // 根据参与人员 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getManager())) {
                List<String> applySql1 = new ArrayList<>();
                String[] arr = xjbWeeklyParam.getManager().split(",");
                for (int i = 0; i < arr.length; i++) {
                    applySql1.add(String.format("(manager like '%%%s%%')", arr[i]));  // 2个%保留一个
                    if (i < arr.length - 1) {
                        applySql1.add(" and ");
                    }
                }
                queryWrapper.apply(" 1=1 and (" + String.join("", applySql1) + ")");
            }
            // 根据关联系统 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getSysids())) {
//                queryWrapper.lambda().in(XjbWeekly::getSysids, xjbWeeklyParam.getSysids());
                List<String> applySql1 = new ArrayList<>();
                String[] arr = xjbWeeklyParam.getSysids().split(",");
                for (int i = 0; i < arr.length; i++) {
                    applySql1.add(String.format("(sysids like '%%%s%%')", arr[i]));  // 2个%保留一个
                    if (i < arr.length - 1) {
                        applySql1.add(" and ");
                    }
                }
                queryWrapper.apply(" 1=1 and (" + String.join("", applySql1) + ")");
            }
            // 根据开始日期 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getStartdate())) {
                queryWrapper.lambda().ge(XjbWeekly::getStartdate, xjbWeeklyParam.getStartdate());
            }
            // 根据结束日期 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getEnddate())) {
                queryWrapper.lambda().le(XjbWeekly::getEnddate, xjbWeeklyParam.getEnddate());
            }
            // 根据目前阶段 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getStage())) {
                queryWrapper.lambda().le(XjbWeekly::getStage, xjbWeeklyParam.getStage());
            }
            // 根据任务整体进度 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getProcess())) {
                queryWrapper.lambda().eq(XjbWeekly::getProcess, xjbWeeklyParam.getProcess());
            }
            // 根据上线日期 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getProduct())) {
                queryWrapper.lambda().eq(XjbWeekly::getProduct, xjbWeeklyParam.getProduct());
            }
            // 根据关联任务 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getRef())) {
                queryWrapper.lambda().eq(XjbWeekly::getRef, xjbWeeklyParam.getRef());
            }
            // 根据有效性 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getVflag())) {
                queryWrapper.lambda().eq(XjbWeekly::getVflag, xjbWeeklyParam.getVflag());
            }
            // 根据备注 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getNote())) {
                queryWrapper.lambda().like(XjbWeekly::getNote, xjbWeeklyParam.getNote());
            }
            // 根据其他信息 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getOthers())) {
                queryWrapper.lambda().like(XjbWeekly::getOthers, xjbWeeklyParam.getOthers());
            }
            // 根据是否关闭 查询
            if (ObjectUtil.isNotEmpty(xjbWeeklyParam.getComplate())) {
                queryWrapper.lambda().eq(XjbWeekly::getComplate, xjbWeeklyParam.getComplate());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<XjbWeekly> list(XjbWeeklyParam xjbWeeklyParam) {
        return this.list();
    }

    @Override
    public void add(XjbWeeklyParam xjbWeeklyParam) {
        XjbWeekly xjbWeekly = new XjbWeekly();
        BeanUtil.copyProperties(xjbWeeklyParam, xjbWeekly);
        this.save(xjbWeekly);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<XjbWeeklyParam> xjbWeeklyParamList) {
        xjbWeeklyParamList.forEach(xjbWeeklyParam -> {
            this.removeById(xjbWeeklyParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(XjbWeeklyParam xjbWeeklyParam) {
        XjbWeekly xjbWeekly = this.queryXjbWeekly(xjbWeeklyParam);
        BeanUtil.copyProperties(xjbWeeklyParam, xjbWeekly);
        this.updateById(xjbWeekly);
    }

    @Override
    public XjbWeekly detail(XjbWeeklyParam xjbWeeklyParam) {
        return this.queryXjbWeekly(xjbWeeklyParam);
    }

//    @Override
//    public void export(XjbWeeklyParam xjbWeeklyParam) {
//        List<XjbWeekly> list = this.list(xjbWeeklyParam);
//        PoiUtil.exportExcelWithStream("SnowyXjbWeekly.xls", XjbWeekly.class, list);
//    }

    /**
     * 获取周报汇总表
     *
     * @author zhangping
     * @date 2022-03-11 10:48:51
     */
    private XjbWeekly queryXjbWeekly(XjbWeeklyParam xjbWeeklyParam) {
        XjbWeekly xjbWeekly = this.getById(xjbWeeklyParam.getId());
        if (ObjectUtil.isNull(xjbWeekly)) {
            throw new ServiceException(XjbWeeklyExceptionEnum.NOT_EXIST);
        }
        return xjbWeekly;
    }

    @Override
    public void export(XjbWeeklyParam xjbWeeklyParam) throws Exception {
        String exportGroup = xjbWeeklyParam.getExportGroup();
        String exportType = xjbWeeklyParam.getExportType();
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUserWithoutException();
        String account = sysLoginUser.getAccount();
        LoginEmpInfo loginEmpInfo = sysLoginUser.getLoginEmpInfo();
        List<XjbWeekly> list = this.list();
        List<XjbWeekly> filterlist = new ArrayList<>();
        //////////////
        if ("person".equalsIgnoreCase(exportGroup) || StrUtil.isBlankIfStr(exportGroup)) {
            filterlist = list.stream().filter(n ->
                    new cn.hutool.json.JSONArray(n.getManager()).contains(account)
            ).collect(Collectors.toList());
        } else if ("team".equalsIgnoreCase(exportGroup)) {
            filterlist = list.stream().filter(n ->
                    n.getOrgs().equalsIgnoreCase("" + loginEmpInfo.getOrgId())
            ).collect(Collectors.toList());
        } else if ("group".equalsIgnoreCase(exportGroup)) {
            SysOrgParam sysOrgParam = new SysOrgParam();
            sysOrgParam.setId(loginEmpInfo.getOrgId());
            SysOrg sysOrg = querySysOrg(sysOrgParam);
            List<Long> childIdList = getChildIdListById(sysOrg.getPid()); // PID
            childIdList.add(sysOrg.getPid());
            filterlist = list.stream().filter(n ->
                    childIdList.contains(Long.valueOf(n.getOrgs()))
            ).collect(Collectors.toList());
        }

        //////////////////////////
        if ("excel".equalsIgnoreCase(exportType)) {
            PoiUtil.exportExcelWithStream("SnowyXjbWeekly.xls", XjbWeekly.class, filterlist);
        } else if ("word".equalsIgnoreCase(exportType)) {
            String template = FileUtil.getUserHomePath() + "/xjbweekly.template.docx";
            String word_name = RandomUtil.randomString(4) + ".docx";
            Map<String, Object> data = getWordData(sysLoginUser, filterlist);
            String html = (String) data.get("html");
            ZpWordUtil.htmlExportWord(html, (String) data.get("word"));
//            ZpWordUtil.exportWordWithStream(word_name, new File(template), data);
        } else {
            throw new NoSuchMethodException("exportType error!");
        }
    }

    @Resource
    private SysDictTypeService sysDictTypeService;

    private Map<String, Object> getWordData(SysLoginUser sysLoginUser, List<XjbWeekly> filterlist) {
        Map<String, Object> data = new HashMap<>();
        SysDictTypeParam sysDictTypeParam = new SysDictTypeParam();
        sysDictTypeParam.setCode("xjb_xjbweekly_tpl");//周报模板
        List<Dict> dict = sysDictTypeService.dropDown(sysDictTypeParam);

//        SysDictDataParam sysDictDataParam = new SysDictDataParam();
//        sysDictDataParam.setTypeId(sysDictType.getId()); ///
//        List<SysDictData> list = sysDictDataService.list(sysDictDataParam);

        String html = get_value("xjbweekly.template", dict); //
        String zizhukaifa = get_value("zizhukaifa", dict); //
        String xiangmugenzong = get_value("xiangmugenzong", dict); //
        String xitongyunwei = get_value("xitongyunwei", dict); //
        String qitarenwu = get_value("qitarenwu", dict); //
        String xiazhougongzuojihua = get_value("xiazhougongzuojihua", dict); //

        List<XjbWeekly> zizhukaifa_list = filterlist.stream().filter(n -> "zizhukaifa".equalsIgnoreCase(n.getType())).collect(Collectors.toList());
        List<XjbWeekly> xiangmugenzong_list = filterlist.stream().filter(n -> "xiangmugenzong".equalsIgnoreCase(n.getType())).collect(Collectors.toList());
        List<XjbWeekly> xitongyunwei_list = filterlist.stream().filter(n -> "xitongyunwei".equalsIgnoreCase(n.getType())).collect(Collectors.toList());
        List<XjbWeekly> qitarenwu_list = filterlist.stream().filter(n -> "qitarenwu".equalsIgnoreCase(n.getType())).collect(Collectors.toList());

        String zizhukaifa_html = renderToString(zizhukaifa, zizhukaifa_list);
        String xiangmugenzong_html = renderToString(xiangmugenzong, xiangmugenzong_list);
        String xitongyunwei_html = renderToString(xitongyunwei, xitongyunwei_list);
        String qitarenwu_html = renderToString(qitarenwu, qitarenwu_list);
        String xiazhougongzuojihua_html = renderToString(xiazhougongzuojihua, qitarenwu_list);

        data.put("周报名称", "科技信息部软件开发组个人周报");
        data.put("小组名称", sysLoginUser.getLoginEmpInfo().getOrgName());
        data.put("报告日期", DateUtil.today());
        data.put("姓名", sysLoginUser.getName());
        data.put("sysLoginUser", sysLoginUser);
        data.put("word", "xxxx的周报.docx");

        data.put("zizhukaifa_num", zizhukaifa_list.size());
        data.put("xiangmugenzong_num", xiangmugenzong_list.size());
        data.put("xitongyunwei_num", xitongyunwei_list.size());
        data.put("qitarenwu_num", qitarenwu_list.size());

        data.put("zizhukaifa", zizhukaifa_html);
        data.put("xiangmugenzong", xiangmugenzong_html);
        data.put("xitongyunwei", xitongyunwei_html);
        data.put("qitarenwu", qitarenwu_html);
        data.put("xiazhougongzuojihua", xiazhougongzuojihua_html);
        ///////////////////////
        data.put("html", getEngine(html).getTemplateByString(html).renderToString(data));
        ///////////////////////
        return data;
    }


    @Resource
    private SysDictDataService sysDictDataService;

    private static String get_value(String code, List<Dict> list) {
        return list.stream().filter(n -> code.equals(n.getStr("code"))).map(n -> n.getStr("value")).collect(Collectors.toList()).get(0);
    }

//    private static String get_value(String code, List<SysDictData> list) {
//        return list.stream().filter(n -> code.equals(n.getCode())).map(n -> n.getValue()).collect(Collectors.toList()).get(0);
//    }

    private static String renderToString(String templatestsr, List<XjbWeekly> list) {
        StringBuffer sb = new StringBuffer();
        Template template = getEngine(templatestsr).getTemplateByString(templatestsr);
        int a = 1;
        for (XjbWeekly xjb : list) {
            sb.append(template.renderToString(
                    Kv.by("index", a++).set("string", xjb.getTitle())
            ));
        }
        return sb.toString();
    }

    private static Engine getEngine(String name) {
        String md5 = DigestUtil.md5Hex(name);
        Engine.setChineseExpression(true);
        Engine engine = Engine.use(md5);
        if (null == engine) {
            engine = Engine.create(md5);
            engine.setDevMode(true);
            engine.setToClassPathSourceFactory();
        }
        return engine;
    }

    private SysOrg querySysOrg(SysOrgParam sysOrgParam) {
        SysOrg sysOrg = sysOrgService.getById(sysOrgParam.getId());
        if (ObjectUtil.isNull(sysOrg)) {
            throw new ServiceException(SysOrgExceptionEnum.ORG_NOT_EXIST);
        }
        return sysOrg;
    }

    private List<Long> getChildIdListById(Long id) {
        List<Long> childIdList = CollectionUtil.newArrayList();
        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(SysOrg::getPids, SymbolConstant.LEFT_SQUARE_BRACKETS + id +
                SymbolConstant.RIGHT_SQUARE_BRACKETS);
        sysOrgService.list(queryWrapper).forEach(sysOrg -> childIdList.add(sysOrg.getId()));
        return childIdList;
    }

    @Override
    public String sort(JSONArray parseArray) {
        List<String> str = new ArrayList(parseArray);
        Collections.sort(str); ///排序
        List<Object> obj = new ArrayList(str);
        return new JSONArray(obj).toString();
    }

//    @Data
//    class Vk implements Serializable {
//        private int index;
//        private String str;
//
//        public Vk(int index, String str) {
//            this.index = index;
//            this.str = str;
//        }
//    }

//    public static void main(String[] args) {
//        String t = "[\"eererr\",\"xuyuxiang\",\"dongxiayu\"]";
//        String cc = new XjbWeeklyServiceImpl().sort(JSONArray.parseArray(t));
//        System.out.println(cc);
//    }
}
